package com.csgc.camera.widget.dialog.base

import android.content.Context
import android.view.*
import android.widget.FrameLayout
import androidx.annotation.FloatRange
import androidx.annotation.LayoutRes
import androidx.annotation.StyleRes
import androidx.appcompat.app.AppCompatDialog
import com.cysd.spsyxj.R


open class BaseDialog constructor(context: Context, @StyleRes themeResId: Int = R.style.BaseDialogTheme):AppCompatDialog(context,themeResId) {


    /**
     * 获取 Dialog 的根布局
     */
    open fun getContentView(): View? {
        val contentView: View? = findViewById(Window.ID_ANDROID_CONTENT)
        if (contentView is ViewGroup && contentView.childCount == 1) {
            return contentView.getChildAt(0)
        }
        return contentView
    }


    /**
     * 设置布局
     */
    override fun setContentView(@LayoutRes id: Int){
        // 这里解释一下，为什么要传 new FrameLayout，因为如果不传的话，XML 的根布局获取到的 LayoutParams 对象会为空，也就会导致宽高参数解析不出来
        return setContentView(LayoutInflater.from(context).inflate(id, FrameLayout(context), false) )
    }

    /**
     * 设置 Dialog 宽度
     */
    open fun setWidth(width: Int) {
        val window: Window = window ?: return
        val params: WindowManager.LayoutParams? = window.attributes
        params?.width = width
        window.attributes = params


        val paramsContent: ViewGroup.LayoutParams? = getContentView()?.layoutParams
        if (paramsContent != null) {
            paramsContent.width = width
            getContentView()?.layoutParams = paramsContent
        }
    }

    /**
     * 设置 Dialog 高度
     */
    open fun setHeight(height: Int) {
        val window: Window = window ?: return
        val params: WindowManager.LayoutParams? = window.attributes
        params?.height = height
        window.attributes = params

        val paramsContent: ViewGroup.LayoutParams? = getContentView()?.layoutParams
        if (paramsContent != null) {
            paramsContent.height = height
            getContentView()?.layoutParams = paramsContent
        }
    }

    /**
     * 设置 Dialog 的动画
     */
    open fun setWindowAnimations(@StyleRes id: Int) {
        window?.setWindowAnimations(id)
    }
    /**
     * 设置 Dialog 重心
     */
    open fun setGravity(gravity: Int) {
        window?.setGravity(gravity)
    }

    /**
     * 设置背景遮盖层开关
     */
    open fun setBackgroundDimEnabled(enabled: Boolean) {
        if (enabled) {
            window?.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        } else {
            window?.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        }
    }

    /**
     * 设置背景遮盖层的透明度（前提条件是背景遮盖层开关必须是为开启状态）
     */
    open fun setBackgroundDimAmount(@FloatRange(from = 0.0, to = 1.0) dimAmount: Float) {
        window?.setDimAmount(dimAmount)
    }


}